package com.spc.car.core.framework.controller.sys;

import com.spc.car.core.framework.aspectj.lang.annotation.Log;
import com.spc.car.core.framework.aspectj.lang.enums.BusinessType;
import com.spc.car.core.framework.util.SecurityUtils;
import com.spc.car.core.framework.web.controller.BaseController;
import com.spc.car.core.framework.web.domain.AjaxResult;
import com.spc.car.data.constant.UserConstants;
import com.spc.car.data.domain.sys.TreeSysDeptNode;
import com.spc.car.data.domain.sys.vo.SysUserShortVO;
import com.spc.car.data.entity.sys.SysDept;
import com.spc.car.data.entity.sys.SysUser;
import com.spc.car.data.service.sys.SysDeptService;
import com.spc.car.data.service.sys.SysUserService;
import com.spc.car.service.domain.dto.DepartmentUserTreeDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门信息
 * 
 * @author
 */
@Validated
@Api(tags = "部门")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController
{
    @Autowired
    private SysDeptService deptService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * 获取部门列表
     */
    @ApiOperation(value = "获取部门列表", notes = "获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @ApiOperation(value = "根据部门编号获取详细信息", notes = "根据部门编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @ApiOperation(value = "获取部门下拉树列表", notes = "获取部门下拉树列表")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(toTreeNode(depts)));
    }

    /**
     * 获取当前用户除自己部门外的其他同级部门
     */
    @ApiOperation(value = "获取当前用户除自己部门外的其他同级部门", notes = "获取当前用户除自己部门外的其他同级部门")
    @GetMapping("/treeSelectExceptSelf")
    public AjaxResult treeSelectExceptSelf()
    {
        SysUser user = getPrintUser();
        //查询出处自己外的同级部门ID
        List<SysDept> depts = deptService.selectDeptListExceptSelf(user.getDeptId());
        //构建前端需要的树
        List<DepartmentUserTreeDTO> departmentUserTreeDTOS = new ArrayList<>();
        depts.stream().forEach(anDept ->{
            DepartmentUserTreeDTO departmentUserTreeDTO = new DepartmentUserTreeDTO();
            departmentUserTreeDTO.setDeptId(anDept.getDeptId());
            departmentUserTreeDTO.setDeptName(anDept.getDeptName());
            departmentUserTreeDTO.setCollaborativeCause(anDept.getCollaborativeCause());
            //查询该部门下的用户
            List<SysUser> deptUsers = sysUserService.selectUserListByDeptId(anDept.getDeptId());
            if (deptUsers.isEmpty()){
                return;
            }
            List<SysUserShortVO> sysUserShortVOS = new ArrayList<>();
            deptUsers.stream().forEach( anDeptUser ->{
                SysUserShortVO sysUserShortVO = new SysUserShortVO();
                BeanUtils.copyProperties(anDeptUser, sysUserShortVO);
                sysUserShortVOS.add(sysUserShortVO);
            });
            departmentUserTreeDTO.setChild(sysUserShortVOS);
            departmentUserTreeDTOS.add(departmentUserTreeDTO);
        });

        return AjaxResult.success(departmentUserTreeDTOS);
    }

    /**
     * 加载对应角色部门列表树
     */
    @ApiOperation(value = "角色部门列表树", notes = "角色部门列表树")
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());

        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(toTreeNode(depts)));
        return ajax;
    }

    /**
     * 新增部门
     */
    @ApiOperation(value = "新增部门", notes = "新增部门")
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @ApiOperation(value = "修改部门", notes = "修改部门")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(dept.getDeptId()))
        {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @ApiOperation(value = "删除部门", notes = "删除部门")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    List<TreeSysDeptNode> toTreeNode(List<SysDept> depts) {
        List<TreeSysDeptNode> listTreeSysDeptNode = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(depts)) {
            depts.stream().forEach(a -> {
                TreeSysDeptNode treeSysDeptNode = new TreeSysDeptNode();
                BeanUtils.copyProperties(a, treeSysDeptNode);
                listTreeSysDeptNode.add(treeSysDeptNode);
            });
        }
        return listTreeSysDeptNode;
    }
}
